from django.shortcuts import (render, HttpResponse, redirect)
from django.views import View
from app01 import models
from app01.utils.book_form import BookForm
from app01.utils.book_form import BookModelForm


def book_list(request):
    books = models.Book.objects.all

    # return HttpResponse('ok')
    return render(request, "book_list.html", locals())


class add_book(View):
    """添加页面通过form组件来做"""

    def get(self, request):
        # publish_list = models.Publish.objects.all()
        # author_list = models.Author.objects.all()
        form = BookForm()
        return render(request, 'add_book.html', locals())

    def post(self, request):
        # print(request.POST)
        # 方式1
        # author_id_list = request.POST.getlist('authors')
        # book_data = request.POST.dict()
        # book_data.pop('authors')

        # 方式2
        # request.POST._mutable = True  #让QueryDict可变
        # data = request.POST.copy()
        # author_id_list = data.pop('authors')
        # book_data = data.dict()
        # book_obj = models.Book.objects.create(**book_data)
        # book_obj.authors.add(*author_id_list)

        form = BookForm(data=request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            authors_objs = form.cleaned_data.pop('authors')
            book_obj = models.Book.objects.create(
                **form.cleaned_data
            )
            book_obj.authors.add(*authors_objs)
            return redirect('book_list')
        else:
            return render(request, 'add_book.html', locals())


class edit_book(View):
    """modelform组件来做"""

    def get(self, request, pk):
        old_book_obj = models.Book.objects.filter(pk=pk).first()
        # publish_list = models.Publish.objects.all()
        # author_list = models.Author.objects.all()

        form = BookModelForm(instance=old_book_obj)

        return render(request, 'edit_book.html', locals())

    def post(self, request, pk):
        old_book_obj = models.Book.objects.filter(pk=pk).first()
        #
        # authors_id_list = request.POST.getlist('authors')
        # data = request.POST.dict()
        # data.pop('authors')
        # old_book_obj.update(**data)
        # old_book_obj.first().authors.set(authors_id_list)

        # 调用modelform方式
        # 如果没有传instance=old_book_obj，那么form.save()做的是添加记录的动作，
        # 如果传了instance=old_book_obj，那么form.save()就是一个修改动作
        form = BookModelForm(data=request.POST, instance=old_book_obj)
        if form.is_valid():
            print(form.cleaned_data)
            form.save()
            return redirect('book_list')
        else:
            return render(request, "edit_book.html", locals())


"""
# 合并添加和编辑
class AddEdit(View):
    def get(self, request, pk=None):
        old_book_obj = models.Book.objects.filter(pk=pk)
        publish_list = models.Publish.objects.all()
        author_list = models.Author.objects.all()
        if old_book_obj.exists():
            old_book_obj = old_book_obj.first()
            return render(request, 'add_edit.html', locals())
        else:
            return render(request, 'add_edit.html', locals())

    def post(self, request, pk=None):
        old_book_obj = models.Book.objects.filter(pk=pk)
        authors_id_list = request.POST.getlist('authors')
        data = request.POST.dict()
        data.pop('authors')
        book_data = data
        if old_book_obj.exists():
            old_book_obj.update(**book_data)
            old_book_obj.first().authors.set(authors_id_list)
        else:
            book_obj = models.Book.objects.create(**book_data, )
            book_obj.authors.add(*authors_id_list)
        return redirect('book_list')
"""


def del_book(request, pk):
    models.Book.objects.filter(pk=pk).delete()
    return redirect('book_list')


def ajax_del_book(request, pk):
    pk = 1000
    try:
        models.Book.objects.get(pk=pk).delete()
    except:
        # return HttpResponse('error')  # 默认响应状态码为200
        return HttpResponse('找不到对应资源', status=404)  # 将默认响应状态码改为404
    return HttpResponse('ok')


